package com.robusta.app.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import java.io.IOException;

public class RequestAndResponseLogger implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestAndResponseLogger.class);
    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logRequest(servletRequest);
        filterChain.doFilter(servletRequest, servletResponse);
        logResponse(servletResponse);
    }

    private void logResponse(ServletResponse servletResponse) {
        LOGGER.info(String.format("Sending response: %s", servletResponse));
    }

    private void logRequest(ServletRequest servletRequest) {
        LOGGER.info(String.format("Received request: %s", servletRequest));
    }

    public void destroy() {
        this.filterConfig = null;
    }
}
